package com.example.smartmedicalsystem.config;

import com.example.smartmedicalsystem.service.CustomUserDetailsService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final CustomUserDetailsService userDetailsService;
    private final CustomAuthenticationSuccessHandler successHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder());
        return provider;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                // 允许访问所有静态资源（包括 admin.html/doctor.html/patient.html）
                .antMatchers(
                        "/",
                        "/index.html",
                        "/login.html",
                        "/register.html",
                        "/ai-chat.html",
                        "/diagnosis.html",
                        "/medical-record.html",
                        "/medicine-management.html",
                        "/admin.html",// 新增管理员页面权限
                        "/doctor.html",   // 新增医生页面权限
                        "/patient.html",  // 新增患者页面权限
                        "/css/**",
                        "/js/**",
                        "/images/**",
                        "/api/public/**"
                ).permitAll()
                // 角色权限配置（访问 API 接口时验证角色）
                .antMatchers("/admin/**", "/api/admin/**").hasRole("ADMIN")
                .antMatchers(HttpMethod.GET, "/api/admin/**").hasRole("ADMIN")
                .antMatchers(HttpMethod.POST, "/api/admin/**").hasRole("ADMIN")
                .antMatchers("/doctor/**", "/api/doctor/**").hasRole("DOCTOR")
                .antMatchers("/patient/**", "/api/patient/**").hasRole("PATIENT")
                .anyRequest().authenticated()  // 其他请求需认证，但静态页面已在上方放行
                .and()
                .formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .successHandler(successHandler)
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login.html")
                .permitAll()
                .and()
                .rememberMe()
                .key("uniqueAndSecretKey")
                .tokenValiditySeconds(86400);

        return http.build();
    }
}